from rest_framework_jwt.authentication import JSONWebTokenAuthentication
import jwt
from rest_framework_jwt.settings import api_settings
jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
from rest_framework import exceptions
from user import models


class MyAuth(JSONWebTokenAuthentication):
    def authenticate(self, request):
        jwt_value = str(request.META.get('HTTP_AUTHORIZATION')).split(' ')[-1]
        try:
            payload = jwt_decode_handler(jwt_value)
            user =  models.UserInfo.objects.filter(pk=payload.get('user_id')).first()
        except jwt.ExpiredSignature:
            msg = '签名过期'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.DecodeError:
            msg = '签名错误'
            raise exceptions.AuthenticationFailed(msg)
        except jwt.InvalidTokenError:
            raise exceptions.AuthenticationFailed('未知错误')

        return (user, jwt_value)